package com.javasm.util;


import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//静态工具方法获取 request、response、session、servletContext
@Component
public class RequestServletUtil {
    public static ServletRequestAttributes getRequestAttributes(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes==null)return null;
        return (ServletRequestAttributes)requestAttributes;
    }

    public static String getParameter(String key,String defaultValue){
        String value = getRequest().getParameter(key);
        if(value==null)return defaultValue;
        return value;
    }

    public static Integer getParameter(String key,Integer defaultValue){
        String value = getRequest().getParameter(key);
        if(value==null)return defaultValue;
        return Integer.parseInt(value);
    }

    public static Double getParameter(String key,Double defaultValue){
        String value = getRequest().getParameter(key);
        if(value==null)return defaultValue;
        return Double.parseDouble(value);
    }

    public static HttpServletRequest getRequest(){
        return getRequestAttributes().getRequest();
    }
    public static HttpServletResponse getResponse(){
        return getRequestAttributes().getResponse();
    }
    public static HttpSession getSession(){
        return getRequest().getSession();
    }
    public static ServletContext getServletContext(){
        return getRequest().getServletContext();
    }

    public static void main(String[] args) {

        //在这个静态工具方法调用容器中某个session对象
        HttpSession session = RequestServletUtil.getSession();
        System.out.println(session);

    }
}
